<template>
  <div class="floating-assistant" :class="{ 'expanded': isExpanded }">
    <!-- 语音助手图标 -->
    <div class="assistant-icon" @mouseenter="isExpanded = true">
      <i class="el-icon-microphone"></i>
    </div>
    
    <!-- 展开的语音助手面板 -->
    <div class="assistant-panel" @mouseleave="isExpanded = false">
      <!-- 语音助手按钮 -->
      <el-button
          class="voice-button"
          @click="toggleVoiceAssistant"
          :type="isListening ? 'danger' : 'primary'"
      >
        <i class="el-icon-microphone"></i>
        {{ isListening ? '停止语音' : '语音助手' }}
      </el-button>

      <!-- 语音状态提示 -->
      <div v-if="voiceStatusText" class="voice-status">
        {{ voiceStatusText }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';

// 语音识别对象
const recognition = ref(null);
const isListening = ref(false);
const voiceStatusText = ref('');
const isExpanded = ref(false);

// 获取路由实例
const router = useRouter();

// 导航函数
const navigateTo = (path) => {
  try {
    router.push(path);
  } catch (error) {
    console.error('导航错误:', error);
    speak('导航失败，请重试');
  }
};

// 退出登录
const logout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('type');
  window.location.href = '/';
  speak('已退出登录');
};

// 初始化语音识别
const initSpeechRecognition = () => {
  if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    recognition.value = new SpeechRecognition();
    recognition.value.continuous = false; // 单次识别
    recognition.value.lang = 'zh-CN';     // 中文识别

    // 识别结果处理
    recognition.value.onresult = (event) => {
      const transcript = event.results[0][0].transcript.trim();
      handleVoiceCommand(transcript);
    };

    // 错误处理
    recognition.value.onerror = (event) => {
      ElNotification({ title: '语音识别错误', message: event.error, type: 'error' });
      isListening.value = false;
    };
  } else {
    ElNotification({ title: '提示', message: '当前浏览器不支持语音功能', type: 'warning' });
  }
};

// 开关语音识别
const toggleVoiceAssistant = () => {
  if (!recognition.value) {
    ElNotification({ title: '错误', message: '语音功能未初始化', type: 'error' });
    return;
  }
  if (!isListening.value) {
    recognition.value.start();
    voiceStatusText.value = '请说出指令...';
    isListening.value = true;
  } else {
    recognition.value.stop();
    isListening.value = false;
    voiceStatusText.value = '';
  }
};

// 语音指令处理
const handleVoiceCommand = (command) => {
  voiceStatusText.value = `识别到指令："${command}"`;
  isListening.value = false;

  // 全局通用指令匹配
  const actions = {
    '返回首页': () => window.location.href = '/',
    '帮助': () => speak('您可以尝试说：返回首页、查看个人信息、社保查询等'),
    '查看个人信息': () => navigateTo('/user/profile'),
    '社保查询': () => navigateTo('/user/index/welcome'),
    '退出登录': () => logout(),
  };

  const matchedAction = Object.keys(actions).find(key => command.includes(key));
  if (matchedAction) {
    actions[matchedAction]();
    speak(`已执行：${matchedAction}`);
  } else {
    speak('未识别到指令，请重试');
  }
};

// 语音播报
const speak = (text) => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'zh-CN';
    utterance.rate = 0.9; // 语速调慢
    window.speechSynthesis.speak(utterance);
  }
};

// 初始化
onMounted(() => {
  initSpeechRecognition();
  // speak('欢迎使用社保系统，点击麦克风按钮开始语音操作'); // 首次进入提示
});
</script>

<style scoped>
/* 浮动助手容器 */
.floating-assistant {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1000;
  display: flex;
  align-items: center;
}

/* 助手图标 */
.assistant-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4f46e5, #7c3aed);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
  transition: all 0.3s ease;
}

.assistant-icon i {
  color: white;
  font-size: 24px;
}

/* 展开面板 */
.assistant-panel {
  position: absolute;
  right: 60px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 10px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  display: none;
  flex-direction: column;
  align-items: center;
  border: 1px solid rgba(79, 70, 229, 0.2);
  backdrop-filter: blur(5px);
  min-width: 250px;
}

/* 展开状态 */
.expanded .assistant-panel {
  display: flex;
  animation: fadeIn 0.3s ease;
}

.expanded .assistant-icon {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateX(10px); }
  to { opacity: 1; transform: translateX(0); }
}

/* 按钮样式 */
.voice-button {
  font-size: 16px;
  padding: 12px 20px;
  margin: 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.voice-status {
  margin: 10px;
  padding: 12px;
  background: #f0f9eb;
  color: #67c23a;
  border-radius: 8px;
  font-size: 14px;
  width: 100%;
  text-align: center;
}
</style>
